package com.teradata

import java.text.SimpleDateFormat
import java.util.Calendar

import org.slf4j.LoggerFactory
import utils.TeradataConnect

@Deprecated
object IopRuleParserMain2 {

  val log = LoggerFactory.getLogger(IopRuleParserMain2.getClass)

  def iopParse(args: Array[String]): Unit = {
    def getLastMonth: String = {
      val dateFormat: SimpleDateFormat = new SimpleDateFormat("yyyyMM")

      val cal: Calendar = Calendar.getInstance()

      cal.setTime(cal.getTime);
      cal.add(Calendar.MONTH, -1)
      val lastMonth = dateFormat.format(cal.getTime())
      lastMonth
    }

    val svcType = args(0)
    log.info("开始解析活动" + svcType + "的配置..")
    log.info("开始连接数据库..")
    //    val conn = (new TeradataConnect).interface177Connect()
    val conn = (new TeradataConnect).portalConnect()
    log.info("数据库已经连接，开始获取此活动相关事件法则..")

    if (svcType.equals("40FC") || svcType.equals("40FA")) {
      val updateSql = s"UPD DBODATA.VGOP_MARKETING_TASKS SET CAL_DATE=DATE WHERE SVC_TYPE='$svcType'"
      val preUpdateSql = conn.prepareStatement(updateSql)
      preUpdateSql.execute()

    }

    val activeActivitySql =
      "  sel A.EVENT_ID" +
        ",A.SVC_TYPE" +
        ",A.EFCT_DATE" +
        ",A.END_DATE" +
        ",B.EVT_ID" +
        ",C.EVT_SORC_TYPE_ID" +
        ",C.RULE_EST_FORMULA" +
        ",C.ARG_LIST" +
        ",A.USER_SQL from ( " +
        "    SEL C.EVENT_ID (TITLE '事件') as EVENT_ID" +
        ",B.SVC_TYPE (TITLE'营销渠道活动编号') as SVC_TYPE" +
        ",A.USER_SQL (TITLE'取营销目标客户的SQL') as USER_SQL" +
        ",MIN(CAST(EFCT_DATE AS DATE FORMAT 'YYYYMMDD') (VARCHAR(8)))  as EFCT_DATE" +
        ",MAX(CAST(END_DATE AS DATE FORMAT 'YYYYMMDD') (VARCHAR(8))) as END_DATE " +
        "  FROM PVIEW.VW_VGOP_MARKETING_TASKS A " +
        "    INNER JOIN VGOPDATA.VW_VGOP_MSUBCHANNEL2 B " +
        "    ON A.SVC_TYPE=B.SVC_TYPE " +
        "  LEFT JOIN VGOPDATA.VW_VGOP_MSUBPLANPOLICY2 C " +
        "    ON B.MPSID=C.MPSID " +
        "  WHERE  B.CHANNEL_TYPE>30 " +
        "  AND CHAR(C.EVENT_ID)>0 " +
        "  AND A.CAL_DATE=DATE " +
        s"  AND A.SVC_TYPE = '$svcType'" +
        "  GROUP BY 1,2,3 " +
        "  )a " +
        "  left join NGBASS.IOP_EVT_SET_EVT_RELAT b " +
        "    on a.EVENT_ID=b.EVT_SET_ID " +
        "  left join NGBASS.IOP_EVT c " +
        "    on B.EVT_ID=C.EVT_ID "

    log.info(activeActivitySql)
    val preActiveActivitySql = conn.prepareStatement(activeActivitySql)
    val activeActivityResultSet = preActiveActivitySql.executeQuery()

    while (activeActivityResultSet.next()) {
      //      本活动对应的事件集id
      //      val evtSetId = activeActivityResultSet.getString(1)
      //      本活动id
      val actId = activeActivityResultSet.getString(2)
      //      本活动客群明细查询sql
      val userPhoneSql = activeActivityResultSet.getString(9)
      //      本活动生效时间
      val efctDate = activeActivityResultSet.getString(3)
      //      本活动实效时间
      val endDate = activeActivityResultSet.getString(4)
      //      事件id
      //      val evtId = activeActivityResultSet.getString(5)
      //      事件源id
      val sourceId = activeActivityResultSet.getString(6)
      //      事件成立公式
      val evtSetEstablishedFormulas = activeActivityResultSet.getString(7)
      //      事件法则列表
      val evtSetEstablishedArgString = activeActivityResultSet.getString(8)

      val evtSetEstablishedArgList = evtSetEstablishedArgString.replaceAll("(?im)\\[|\\]|\"|\\s", "").split(",").toList

      val message = userPhoneSql.replaceAll("(?im)\\s*sel.*?,.*?,\\s*'|'\\s*as\\s+SMS.*", "")

      sourceId match {
        case "4" => selectLocationFunc
//        case "3" => switchPhoneFunc
//        case "2" => changePhonefunc
        case _ => log.error("Cannot found or recognized eventSourceType!")
      }


      def selectLocationFunc: Unit = {
        //===========================清空历史配置、客群、基站临时表信息=======================================
        log.info("查询完毕，开始清空历史配置、客群、基站临时表信息..")
        val delActSql = "del from NMART.VT_IOP_ACT all"
        val delCustSql = "del from NMART.VT_IOP_CUST all"
        val delLacCiSql = "del from NMART.VT_IOP_MP_CELL all"

        val preDelActSql = conn.prepareStatement(delActSql)
        val preDelCustSql = conn.prepareStatement(delCustSql)
        val preDelLacCiSql = conn.prepareStatement(delLacCiSql)

        preDelActSql.execute()
        preDelCustSql.execute()
        preDelLacCiSql.execute()
        //===========================清空历史配置、客群、基站临时表信息=======================================

        //===========================计算此活动配置信息=======================================

        log.info("清空完毕，开始计算此活动配置信息..")
        val actSql = s"insert into NMART.VT_IOP_ACT sel '$actId','$message','$efctDate','$endDate'"
        log.info(actSql)
        val preActSql = conn.prepareStatement(actSql)
        preActSql.execute()
        //===========================计算此活动配置信息=======================================


        //===========================计算此活动客群=======================================
        log.info("计算完毕，开始计算此活动客群..")
        val lastMonth = getLastMonth
        val custSql = userPhoneSql
          .replaceAll(s"(?im)\\s*sel.*?,.*?,\\s*'.*?'\\s+as\\s+SMS"
            , s"insert into NMART.VT_IOP_CUST SELECT SUBSTR(TRIM(MSISDN),10,11)||TRIM(MSISDN) ,'$lastMonth'")
        log.info(custSql)
        val preCustSql = conn.prepareStatement(custSql)
        preCustSql.execute()
        //===========================计算此活动客群=======================================

        //===========================计算此活动基站列表=======================================
        log.info("计算完毕，开始计算此活动基站列表..")
        evtSetEstablishedArgList.foreach(ruleId => {

          val formulasSql = s"SEL CAST(PRINC_ARG AS VARCHAR(10000)) FROM ngbass.iop_rule WHERE rule_id ='$ruleId'"
          log.info(formulasSql)
          val preFormulasSql = conn.prepareStatement(formulasSql)
          val formulasResultSet = preFormulasSql.executeQuery()
          var lacciList = ""
          while (formulasResultSet.next()) {
            lacciList = formulasResultSet.getString(1)
          }
          val insertLacciActIdSql = "insert into NMART.VT_IOP_MP_CELL values(?)"
          val preInsertLacciActIdSql = conn.prepareStatement(insertLacciActIdSql)
          lacciList.replaceAll("(?im)\\[|\\]|\"|\\s", "")
            .split(",")
            .map(_ + "-" + actId)
            .foreach(lacciActId => {
              preInsertLacciActIdSql.setString(1, lacciActId)
              preInsertLacciActIdSql.addBatch()
            })
          preInsertLacciActIdSql.executeBatch()

        })

        //===========================计算此活动基站列表=======================================
      }



    }



    conn.close();
    log.info("计算完毕，可以开始同步此活动到hbase。")
  }

}
